import time
from selenium import webdriver
from selenium.webdriver.common.by import By

# 1、打开12306
browser = webdriver.Chrome()
url = 'https://kyfw.12306.cn/otn/resources/login.html'
browser.get(url)
#设置隐式等待时间为10s。（让浏览器完成对页面元素的渲染）
browser.implicitly_wait(10)

# 反爬虫
script = 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined,});'
browser.execute_script(script)

# 2、登录12306
browser.minimize_window()
# ①选择账号登录
browser.find_element(By.XPATH, '//*[@id="toolbar_Div"]/div[2]/div[2]/ul/li[1]/a').click()   # xpath相对路径
time.sleep(1)
# browser.find_element(By.ID, '/html/body/div[1]/div[2]/div[2]/ul/li[1]/a').click()           # xpath绝对路径
# # ②选择扫码登录
# browser.find_element(By.XPATH, '//*[@id="toolbar_Div"]/div[2]/div[2]/ul/li[2]/a').click()
# 传递用户名和密码
username = input('请输入你的用户名：\n')
password = input('请输入你的密码：\n')
browser.find_element(By.ID, 'J-userName').send_keys(username)
browser.find_element(By.ID, 'J-password').send_keys(password)
# 登录
browser.find_element(By.ID, 'J-login').click()
browser.implicitly_wait(1)
browser.maximize_window()
time.sleep(1)
# 短信验证
browser.minimize_window()
browser.find_element(By.XPATH, '//*[@id="verification"]/li[2]/a').click()
id = input('请输入身份证号后四位：\n')
browser.find_element(By.XPATH, '//*[@id="id_card"]').send_keys(id)
browser.find_element(By.XPATH, '//*[@id="verification_code"]').click()
time.sleep(1)
browser.minimize_window()
code = input('请输入验证码：\n')
browser.maximize_window()
browser.find_element(By.XPATH, '//*[@id="code"]').send_keys(code)
browser.find_element(By.XPATH, '//*[@id="sureClick"]').click()
time.sleep(5)

# 3、订票
# 点击车票预定
browser.find_element(By.XPATH, '//*[@id="link_for_ticket"]').click()
fromStation = input('你的出发地：\n')
browser.find_element(By.XPATH, '//*[@id="fromStationText"]').clear()    # 清楚输入框内容
browser.find_element(By.XPATH, '//*[@id="fromStationText"]').send_keys(fromStation)
browser.find_element(By.XPATH, '//*[@id="fromStationText"]').send_keys(Keys.ENTER)  # 下拉框回车确认
toStation = input('你的目的地：\n')
browser.find_element(By.XPATH, '//*[@id="toStationText"]').clear()
browser.find_element(By.XPATH, '//*[@id="toStationText"]').send_keys(toStation)
browser.find_element(By.XPATH, '//*[@id="toStationText"]').send_keys(Keys.ENTER)  # 下拉框回车确认

# 获取打开的多个窗口句柄
windows = browser.window_handles
# 切换到当前最新打开的窗口
browser.switch_to.window(windows[-1])
time.sleep(2)

# 窗口最大化
browser.maximize_window()
time.sleep(2)

browser.find_element(By.XPATH, '//*[@id="query_ticket"]').send_keys()
time.sleep(2)